package com.shao.serialize.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.shao.serialize.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/28 14:10
 */
@Slf4j
public class HessianSerialize implements Serializer {

    @Override
    public byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        }
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            Hessian2Output h2o = new Hessian2Output(baos);
            h2o.writeObject(object);
            h2o.close();
            log.debug("使用hessian序列化对象【{}】完成", object);
            return baos.toByteArray();
        } catch (IOException e) {
            log.error("使用hessian序列化对象时发生异常", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        if (bytes == null || bytes.length == 0 || clazz == null) {
            return null;
        }
        try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) {
            Hessian2Input h2i = new Hessian2Input(bais);
            Object res = h2i.readObject();
            h2i.close();
            log.debug("使用hessian反序列化对象【{}】完成", res);
            return clazz.cast(res);
        } catch (IOException e) {
            log.error("使用hessian反序列化对象时发生异常", e);
            throw new RuntimeException(e);
        }
    }
}
